import pymongo
from model.update_contest.config.config import vj_once_time_sleep
from script.calculate_grade.calculate_grade1.nc_acm_calculate_grade1 import nc_acm_calculate_grade1
from script.get_contest_info.result.vjudge_result import vj_ac_and_time
from model.update_contest.vjudge.use.sort_rule import vj_sort_rule
import time

def vj_update_contest(contest_id):
    client = pymongo.MongoClient("mongodb://localhost:27017/")
    db = client["ACM_MEMBER"]
    collections = db["VJUDGE_INFORMATION"]
    contest_members = []
    for collection in collections.find():
        member = {}
        member["student_id"] = collection["student_id"]
        time.sleep(vj_once_time_sleep)
        member["ac_number"], member["time"]  = vj_ac_and_time(contest_id,collection["vjudge_id"])
        if member["ac_number"] != 0:
            contest_members.append(member)
    contest_members = vj_sort_rule(contest_members)
    # 借用函数
    contest_members = nc_acm_calculate_grade1(contest_members)

    for member in contest_members:
        dict_by = {
            "vjudge_contest" + str(contest_id): {
                "ac_number": member["ac_number"],
                "time": member["time"],
                "grade1": member["grade1"]
            }
        }
        collections.update_one({"student_id": member["student_id"]}, {"$set": dict_by}, upsert=True)
    client.close()

if __name__ == "__main__":
    vj_update_contest(contest_id=641750)